<script setup lang="ts">
import { computed, ref } from 'vue';
import { Box, Collection } from '@element-plus/icons-vue';

const form = ref<any>({});
const packages = ref<any>([]);
interface PayTypeItem {
  value: any;
  label: string;
}
interface OrderFromItem {
  value: any;
  label: string;
}

const props = defineProps<{
  payType: PayTypeItem[];
  orderFrom: OrderFromItem[];
}>();

// Emits
const emit = defineEmits(['update:modelValue', 'confirm']);

const innerVisible = ref(false);

const agreeChecked = ref(false);
// 支付方式
const payTypeText = computed(
  () => props.payType.find((v: any) => v.value === form.value.paymentMethod)?.label || ''
);

// 订单来源
const channelText = computed(() => {
  return props.orderFrom.find((v: any) => v.value === form.value.channelType)?.label || '';
});

const totalQuantity = computed(() =>
  (packages.value || []).reduce((sum: number, p: any) => {
    // p.productCollection 下面的 num 相加
    const qty = (p?.productCollection || []).reduce(
      (s: number, it: any) => s + (Number(it.num) || 0),
      0
    );
    return sum + qty;
  }, 0)
);
const totalAmount = computed(() =>
  (packages.value || []).reduce((sum: number, p: any) => {
    // p.productCollection 下面的 num * salePrice 相加
    const qty = (p?.productCollection || []).reduce(
      (s: number, it: any) => s + (Number(it.num) || 0) * (Number(it.salePrice) || 0),
      0
    );
    return sum + qty;
  }, 0)
);

function calcPkgQty(pkg: any) {
  const qty = (pkg?.productCollection || []).reduce(
    (s: number, it: any) => s + (Number(it.num) || 0),
    0
  );
  return qty;
}
function calcPkgAmount(pkg: any) {
  const qty = (pkg?.productCollection || []).reduce(
    (s: number, it: any) => s + (Number(it.num) || 0) * (Number(it.salePrice) || 0),
    0
  );
  return qty;
}
function formatMoney(n: number) {
  try {
    return (n || 0).toFixed(2);
  } catch {
    return '0.00';
  }
}

function close() {
  innerVisible.value = false;
}

function confirm() {
  close();
  emit('confirm');
}

function show(data: any) {
  packages.value = data.packages;
  form.value = data;
  innerVisible.value = true;
}

defineExpose({
  close,
  show
});
</script>

<template>
  <el-dialog
    v-model="innerVisible"
    :close-on-click-modal="false"
    :show-close="true"
    width="980px"
    top="6vh"
    class="confirm-dialog"
    append-to-body
  >
    <template #header>
      <div class="cd-header">
        <div class="title">
          <span class="emoji">✅</span>
          <div>
            <div class="main">请二次确认订单信息</div>
            <div class="sub">确认无误后再提交，避免错发/漏发</div>
          </div>
        </div>
        <div class="stats">
          <div class="stat">
            <div class="k">包裹数</div>
            <div class="v">{{ packages.length }}</div>
          </div>
          <div class="divider" />
          <div class="stat">
            <div class="k">总件数</div>
            <div class="v">{{ totalQuantity }}</div>
          </div>
          <div class="divider" />
          <div class="stat">
            <div class="k">订单总额</div>
            <div class="v">¥{{ formatMoney(totalAmount) }}</div>
          </div>
        </div>
      </div>
    </template>

    <div class="cd-body">
      <!-- 付款信息概览 -->
      <el-card shadow="never" class="section-card">
        <template #header>
          <div class="section-head">
            <div class="label">
              <el-icon>
                <collection />
              </el-icon>
              付款信息
            </div>
            <el-tag v-if="form.payType" effect="dark">{{ payTypeText }}</el-tag>
          </div>
        </template>
        <!-- 1. 主要信息描述表格 -->
        <el-descriptions :column="3" border size="small" style="margin-bottom: 16px">
          <el-descriptions-item label="客户名称">
            {{ form.receiverName || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="客户电话">
            {{ form.receiverPhone || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ form.orderTime || '—' }}
          </el-descriptions-item>
          <el-descriptions-item :span="4" label="客户地址">
            {{ form.receiverAddress || '—' }}
          </el-descriptions-item>

          <el-descriptions-item label="付款方式">
            {{ payTypeText || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="已付">
            ¥{{ formatMoney(form.actualPrice || 0) }}
          </el-descriptions-item>
          <el-descriptions-item label="代收">
            ¥{{ formatMoney(form.codAmount || 0) }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            <b>¥{{ formatMoney(form.totalAmount || 0) }}</b>
          </el-descriptions-item>

          <el-descriptions-item label="是否大单">
            <el-tag :type="form.isBigOrder ? 'danger' : 'info'" round>
              {{ form.isBigOrder ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="延期发货">
            <el-tag :type="form.isDelayedDelivery ? 'warning' : 'success'" round>
              {{ form.isDelayedDelivery ? '是（发货待通知）' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :span="4" label="订单来源">
            {{ channelText || '未填' }}
          </el-descriptions-item>
          <el-descriptions-item :span="4" label="订单备注">
            {{ form.orderRemark || '未填' }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="form.remark" class="remark">
          <el-alert :closable="false" type="info" show-icon>
            <template #title>
              <span class="remark-title">备注</span>
            </template>
            <div class="remark-content">{{ form.remark }}</div>
          </el-alert>
        </div>
      </el-card>

      <!-- 包裹明细列表 -->
      <el-card shadow="never" class="section-card">
        <template #header>
          <div class="section-head">
            <div class="label">
              <el-icon>
                <box />
              </el-icon>
              包裹明细
            </div>
          </div>
        </template>

        <el-collapse accordion class="pkg-collapse">
          <el-collapse-item
            v-for="(pkg, idx) in packages"
            :key="pkg.id || idx"
            :name="pkg.id || idx"
          >
            <template #title>
              <div class="pkg-title">
                <el-tag type="primary" round>包裹 {{ idx + 1 }}</el-tag>
                <span class="pkg-title-text">
                  <!-- {{ pkg.receiverName || "未填写姓名" }} · -->
                  <!-- {{ pkg.receiverPhone || "未填写电话" }} -->
                </span>
                <span class="addr">
                  <!-- {{
                    pkg.receiverAddress || "未填写地址"
                  }} -->
                </span>
                <el-tag size="small" class="qty-tag"
                  >{{ calcPkgQty(pkg) }} 件 / ¥{{ formatMoney(calcPkgAmount(pkg)) }}</el-tag
                >
              </div>
            </template>

            <div class="pkg-grid">
              <div>
                <el-table
                  :data="pkg.productCollection || []"
                  border
                  size="small"
                  style="width: 100%"
                >
                  <el-table-column label="产品名称" prop="productName" min-width="150" />
                  <el-table-column label="件数" width="100" prop="num"> </el-table-column>
                  <el-table-column label="销售价" width="120" align="right" prop="salePrice">
                  </el-table-column>
                  <el-table-column label="小计" width="120" align="right">
                    <template #default="{ row }"
                      >¥{{ formatMoney((row.num || 0) * (row.salePrice || 0)) }}</template
                    >
                  </el-table-column>
                </el-table>
                <div class="pkg-total">
                  <span>合计：</span>
                  <b>{{ calcPkgQty(pkg) }}</b> 件 ·
                  <b>¥{{ formatMoney(calcPkgAmount(pkg)) }}</b>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <el-alert
        v-if="form.isDelayedDelivery"
        class="delay-tip"
        type="warning"
        :closable="false"
        show-icon
        title="该订单设置为延期发货，系统会转至发货部但不会实际发出。"
        description="若需要改为即时发货，请返回上一步取消‘延期发货’选项。"
      />
    </div>

    <template #footer>
      <div class="cd-footer">
        <div class="left">
          <el-checkbox v-model="agreeChecked">我已逐项核对无误</el-checkbox>
        </div>
        <div class="right">
          <el-button @click="close">返回修改</el-button>

          <el-button type="primary" :disabled="!agreeChecked" @click="confirm">确认提交</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.confirm-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: none;
}

.cd-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.12), rgba(103, 194, 58, 0.08));
  border-radius: 20px;
  padding: 16px 18px;
}

.cd-header .title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cd-header .emoji {
  font-size: 28px;
}

.cd-header .main {
  font-size: 18px;
  font-weight: 700;
}

.cd-header .sub {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.cd-header .stats {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cd-header .stat {
  text-align: center;
  padding: 0 8px;
}

.cd-header .stat .k {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.cd-header .stat .v {
  font-size: 18px;
  font-weight: 800;
}

.cd-header .divider {
  width: 1px;
  height: 24px;
  background: var(--el-border-color-lighter);
}

.cd-body {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.section-card {
  border-radius: 16px;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.section-head .label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 700;
}

.remark {
  margin-top: 10px;
}

.remark-title {
  font-weight: 700;
}

.remark-content {
  white-space: pre-wrap;
}

.pkg-collapse {
  border: 0 !important;
  :deep {
    .el-collapse-item__header {
      border: 0;
    }
  }
}

.pkg-title {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.pkg-title-text {
  font-weight: 600;
}

.pkg-title .addr {
  color: var(--el-text-color-secondary);
  margin-left: 6px;
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.qty-tag {
  margin-left: auto;
}

.pkg-grid {
  display: grid;
  gap: 12px;
}

.pkg-total {
  text-align: right;
  padding: 8px 0 0 0;
  font-size: 13px;
}

.delay-tip {
  margin-top: 8px;
}

.cd-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
</style>
